package com.soft.springhrms.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储对象
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long expireTime) {
        redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
    }

    // 获取对象
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除对象
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    // 延迟双删操作
    public void deleteWithDelay(String key) {
        // 立即删除缓存
        delete(key);

        // 延迟再次删除缓存
        deleteCacheWithDelay(key);
    }

    @Async
    protected void deleteCacheWithDelay(String cacheKey) {
        try {
            Thread.sleep(1000); // 延迟1秒
            delete(cacheKey);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("缓存删除失败", e);
        }
    }
}